import { Op } from 'sequelize';
import Menu from '../model/menu.model';


class MenuService {
    async create({ parent_id, name, icon, orderNum, path, type, extend, show }) {
        const res = await Menu.create({ parent_id, name, icon, orderNum, path, type, extend, show });
        return res.dataValues;
    }
    //根据条件查询菜单
    async findInfo({ name, path }) {
        let whereOpt = {}
        if(name){
            let options = {name}
            let res = await Menu.findOne({
                attributes: ['id', 'name', 'path'],
                where: options
            });
            if(res?.dataValues){
                return res?.dataValues
            }
        }
        if(path){
            let options = {path}
            let res = await Menu.findOne({
                attributes: ['id', 'name','path'],
                where: options
            });
            if(res?.dataValues){
                return res?.dataValues
            }
        }
    }
    //删除
    async delete({ids}){
        const res = await Menu.destroy({ where: { id:ids } })
        return res > 0 ? true : false;
    }
    //更新
    async update({id,name,icon,path,show,orderNum,type,extend}){
        let whereOpt = { id };
        let params = {};
        name && Object.assign(params, { name })
        icon && Object.assign(params, { icon })
        path && Object.assign(params, { path })
        show && Object.assign(params, { show })
        orderNum && Object.assign(params, { orderNum })
        type && Object.assign(params, { type })
        extend && Object.assign(params, { extend })
        const res = await Menu.update(params, { where: whereOpt });
        return res[0] > 0 ? true : false
    }
    //查询列表
    async getList({id='', name='', parent_id='',path='',show=true, size=0, page=0 }) {
        let whereOpt = {};
        name && Object.assign(whereOpt, { name:{[Op.like]: `%${name}%`}})
        id && Object.assign(whereOpt, { id })
        parent_id && Object.assign(whereOpt, { parent_id })
        path && Object.assign(whereOpt, { path })
        show && Object.assign(whereOpt, { show })
        let res:any = null
        if(size && page){
            res = await Menu.findAndCountAll({
                where:whereOpt,
                offset: (page - 1) * size,
                limit: size,
                raw: true,
                order:[
                    ['orderNum','ASC']
                ]
            })
        }else{
            res = await Menu.findAll({
                where:whereOpt,
                raw: true,
                order:[
                    ['orderNum','ASC']
                ]
            })
        }
        return res || null
    }
}

export default new MenuService
